/**
* @Description:（基于高德地图，使用需引用@amap/amap-jsapi-loader ）关键字搜索,点击地图返回位置组件
* @author NewLore1
* @Date 2024/05/15/15:09
* @LastEditors: 乔
* @LastEditTime: 2024/05/15/15:09
**/
<template>
  <div  v-if="isShow">
  <el-dialog title="位置选择"  append-to-body :close-on-click-modal="false" :visible.sync="isShow"  @close="onClose" width="74%">
    <el-row :gutter="2" class="">
      <el-col :span="24">
        <div style="width: 100%">
          <div class="search_box">
            <div class="label">关键字搜索:</div>
            <el-input v-model="input" placeholder="请输入搜索位置信息" id="tipinput"></el-input>
          </div>
          <div ref="gdMap_id" id="gdMap_id" style="width: 100%;height: 400px;"></div>
        </div>
      </el-col>
    </el-row>
      <el-row :gutter="2" class="" style="margin-top:20px">
        <el-form ref="elForm"  :model="dataForm" size="small" label-width="60px" label-position="right">
          <el-col :span="14">
            <el-form-item label="详细地址:" label-width="90px" prop="qLocation">
              <el-input v-model="dataForm.qLocation" placeholder="自动带出" clearable :style="{ width: '100%' }" readonly>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="经度:" prop="qLongitude">
              <el-input v-model="dataForm.qLongitude" placeholder="自动带出" clearable :style="{ width: '100%' }" readonly>
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="5">
            <el-form-item label="纬度:" prop="qLatitude">
              <el-input v-model="dataForm.qLatitude" placeholder="自动带出" clearable :style="{ width: '100%' }" readonly>
              </el-input>
            </el-form-item>
          </el-col>
        </el-form>
    </el-row>
    <span slot="footer" class="dialog-footer">
      <el-button @click="onClose">取 消</el-button>
      <el-button type="primary" @click="onSubmit()" v-if="!isDetail">确 定</el-button>
    </span>
  </el-dialog>
  </div>
</template>
<script>
import AMapLoader from "@amap/amap-jsapi-loader"; //引入AMapLoader
window._AMapSecurityConfig = {
  // 设置安全密钥
  securityJsCode: "4b831c37c54391131a2c2ec3d1afffd6",
};
export default {
  components: {},
  props: {
    /**
     * 默认显示的地图对象信息
     * 地址 经度 纬度
     *  { address: '', lat: '',lng: '',}
     */
    defaultMapData: {
      type: Object,
      default: () => new Object(),
    },
  },
  data () {
    return {
      loading: false,
      isShow: false,
      isDetail: false,
      dataForm: {
        qLocation: undefined,//详细地址
        qLongitude: undefined,
        qLatitude: undefined,
        province:undefined,
        city:undefined,
      },
      input: "",
      map: null,
      auto: null,
      placeSearch: null,
      lnglat: [],
      markers: [],
      position: {},
    };
  },
  computed: {},
  watch: {},
  created () { },
  mounted () {
    this.initMap();
  },
  methods: {
    showMap(){
      this.isShow=true;
      this.initMap();
    },

    // 地图初始化
    initMap () {
      let centerLen = [116.397428, 39.90923];
      AMapLoader.reset()
      AMapLoader.load({
        key: "b37e82608a0ac5e8f8f9e8a402de90bb", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ["AMap.AutoComplete", "AMap.PlaceSearch", "AMap.Geocoder"],
         })
        .then((AMap) => {
          this.map = new AMap.Map("gdMap_id", {
            zoom: 16, // 初始化地图级别
            center: centerLen, //中心点坐标
            resizeEnable: true,
          });
          //父组件传过来的点 默认点位打点
          if (this.defaultMapData.lat && this.defaultMapData.lng) {
            let  setObj={
              lng:this.defaultMapData.lng,
              lat:this.defaultMapData.lat,
            }
            this.lnglat = [setObj.lng,setObj.lat];
            this.setMarker(this.lnglat);
            // 点击地图上的位置，根据经纬度转换成详细地址
            let geocoder = new AMap.Geocoder({});
            let that = this;
            this.dataForm.qLongitude = setObj.lng;
            this.dataForm.qLatitude =setObj.lat;
            geocoder.getAddress(this.lnglat, function (status, result) {
              if (status === "complete" && result.regeocode) {
                let {formattedAddress,addressComponent} = result.regeocode;
                that.dataForm={
                  ...result.regeocode,
                  ...that.dataForm,
                  qLocation: formattedAddress,
                  province:addressComponent.province,
                  city:addressComponent.city?addressComponent.city:addressComponent.province,
                }
              } else {
              }
            });
            this.position = {
              longitude: setObj.lng,
              latitude: setObj.lat,
              address: that.address,
            };
            this.input = that.address; //把查询到的地址赋值到输入框
          }else{
            this.setMarker(centerLen)
          }
          // 关键字查询
          this.searchMap();
          // 监听鼠标点击事件
          this.map.on("click", this.clickMapHandler);
        })
        .catch((e) => { });
    },

    // 关键字查询
    searchMap () {
      // 搜索框自动完成类
      this.auto = new AMap.AutoComplete({
        input: "tipinput", // 使用联想输入的input的id
      });
      //构造地点查询类
      this.placeSearch = new AMap.PlaceSearch({
        map: this.map,
      });
      // 当选中某条搜索记录时触发
      this.auto.on("select", this.selectSite);
    },

    //当选中某条搜索记录时触发
    selectSite (e) {
      if (e.poi.location) {
        // this.lnglat = [e.poi.location.lng, e.poi.location.lat];
        this.placeSearch.setCity(e.poi.adcode);
        this.placeSearch.search(e.poi.name); //关键字查询
        //let geocoder = new AMap.Geocoder({});
        // let that = this;
        // geocoder.getAddress(this.lnglat, function (status, result) {
        //   if (status === "complete" && result.regeocode) {
        //     that.province = result.regeocode.addressComponent.province;
        //     that.city = result.regeocode.addressComponent.city;
        //     //自己想要赋的值，根据自己的做修改
        //     that.$set(that.dataForm, "province", that.province);
        //     that.$set(that.dataForm, "city", that.city);
        //     that.$set(that.dataForm, "address", e.poi.name);
        //     that.$set(that.dataForm, "coordinate", e.poi.location.lng + "," + e.poi.location.lat
        //     ); //纬度，经度
        //   } else {
        //   }
        // });
      } else {
        this.$message.error("查询地址失败，请重新输入地址");
      }
    },

    // 点击地图事件获取经纬度，并添加标记
    clickMapHandler (e) {
      if (this.map.getAllOverlays('marker').length) {
        // 地图已有标注，清除标注
        this.map.clearMap();
      }
      this.dataForm.qLongitude = e.lnglat.getLng();
      this.dataForm.qLatitude = e.lnglat.getLat();
      this.lnglat = [e.lnglat.getLng(), e.lnglat.getLat()];
      this.setMarker(this.lnglat);
      // 点击地图上的位置，根据经纬度转换成详细地址
      let geocoder = new AMap.Geocoder({});
      let that = this;
      geocoder.getAddress(this.lnglat, function (status, result) {
        if (status === "complete" && result.regeocode) {
          let {formattedAddress,addressComponent} = result.regeocode;
          that.dataForm={
            ...result.regeocode,
            ...that.dataForm,
            qLocation: formattedAddress,
            province:addressComponent.province,
            city:addressComponent.city?addressComponent.city:addressComponent.province,
          }
        } else {
        }
      });
      this.position = {
        longitude: e.lnglat.getLng(),
        latitude: e.lnglat.getLat(),
        address: that.address,
      };
      this.input = that.address; //把查询到的地址赋值到输入框
    },

    //添加标记
    setMarker (lnglat) {
      this.removeMarker();
      let marker = new AMap.Marker({
        position: lnglat,
      });
      marker.setMap(this.map);
      this.markers.push(marker);
      this.map.setCenter(lnglat)// 当前标点移动至地图中心
    },

    // 删除之前后的标记点
    removeMarker () {
      if (this.map.getAllOverlays('marker').length) {
        // 地图已有标注，清除标注
        this.map.clearMap();
      }
    },


    //选择经纬度返回
    onSubmit(){
      if(this.dataForm.qLocation && this.dataForm.qLongitude){
        this.isShow = false
        this.$emit('close',this.dataForm)
      }else{
        this.$message.warning('请选择经纬度')
      }
    },
    //取消按钮
    onClose() {
      this.isShow = false;
    }
  },
};
</script>

<style lang="scss" >
.amap-sug-result {
  z-index: 9999 !important;
  visibility: visible;
}
</style>
<style lang="scss" scoped>

::v-deep .el-dialog__body {
  padding: 0px 20px!important;
}


.search_box {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  height: 50px;

  .label {
    width: 100px;
    font-size: 14px;
    color: #606266;
    line-height: 40px;
    font-weight: 700;
  }
}

.content {
  position: relative;
}

#panel {
  position: absolute;
  top: 50px;
  right: 20px;
}

</style>
